<template>
  
  <div class="calendar">
    <div class="headr">
      <div class="dropdown">
        <div class="drop">
          <el-dropdown @command="handleCommandYear">
						<span class="el-dropdown-link">
							{{currentYear}}年 <el-icon><ArrowDown /></el-icon>
						</span>
            <template #dropdown>
              <el-dropdown-menu style="height: 100px">
                <el-dropdown-item :command="year" v-for="year in years" :key="year">{{year}}</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="drop">
          <el-dropdown @command="handleCommandMonth">
              <span class="el-dropdown-link">
                {{currentMonth}}
                <el-icon><ArrowDown /></el-icon>
              </span>
            <template #dropdown>
              <el-dropdown-menu style="height: 100px">
                <el-dropdown-item :command="month" v-for="month in months" :key="month">{{month}}</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <div class="arrow">
        <span @click="prevMonth">
        <el-icon><arrow-left /></el-icon>
        </span>
        <span @click="nextMonth">
          <el-icon><ArrowRight /></el-icon>
        </span>
      </div>
    </div>
    <div class="week">
      <div class="week-item" v-for="i in week" :key="i">{{i}}</div>
    </div>
    <div class="panel-content">
      <!-- 上月天数 -->
      <div class="day-item noCurrentDays" :class="{'weekActiveDay': i.isActive}" v-for="i in prevMonthDays" :key="i + 'A'" @click="handleDay(i)">
        <div>{{i.day}}</div>
      </div>
      <!-- 当月天数 -->
      <div ref="refDay" class="day-item " 
          :class="{'isCurrentDay' : i.day === day, 'isActiveDay': i.date === activeDate, 'weekActiveDay': i.isActive}" 
          v-for="(i) in currentMonthDays" 
          :key="i + 'A'" 
          @click="handleDay(i)"
          >
            <div>{{i.day}}</div>
          </div>
      <div 
        class="day-item noCurrentDays" 
        :class="{'weekActiveDay': i.isActive}" 
        v-for="i in nextMonthDays" 
        :key="i + 'A'" @click="handleDay(i)">
        <div>{{i.day}}</div>
      </div>
    </div>
  </div>


</template>

<script lang='ts'>
import { ArrowRight, ArrowLeft, ArrowDown } from '@element-plus/icons-vue'
import { defineComponent, toRefs, onMounted, reactive, computed, ref, watch } from '@vue/runtime-core'
import {getAllDays} from '.././utils/Date'


const getYearMonthDay = (date = new Date()) => {
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	return { year, month, day };
};

interface Date {
	year: number;
	month: number;
	day: number;
}
export default defineComponent({
  components: {
    ArrowRight,
    ArrowLeft,
    ArrowDown
  },
  props: {
    isActive: {
      type: String
    }
  },
  emits:['getDays', 'getWeeks'],
  setup(props, ctx) {
    

    let week = ['日','一', '二', '三', '四', '五', '六',]
    let years:number[] = []
    let months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    let days = ref(new Array(42).fill({ day: "" }))
    const date: Date = reactive({
			year: 0,
			month: 0,
			day: 0,
		});
    const currentMonth = ref('')
    const currentYear = ref()
    const activeDate = ref('')
    const firstweek = ref('')
    const lastweek = ref('')
    const type = ref(props.isActive)

    // const refDay = ref(null)
    watch(() => props.isActive, (typeDay, prevDay) => {
      console.log(typeDay)
      type.value = typeDay
      if(type.value === 'day') {
        let month = Number(date.month) < 10? '0' + date.month : date.month
        let day = Number(date.day) < 10? '0' + date.day : date.day
        firstweek.value = date.year + '-' + month + '-' + day
        console.log(firstweek.value)
        // 切换类型
        days.value.forEach(item => item.isActive = false)
        ctx.emit('getDays', firstweek.value)
      }

      // 切换周
      if(type.value === 'week') {
        
        weekStartAndEnd(date.year, date.month, date.day, weekday())
      }
    })
    
    const {year} = getYearMonthDay()
    for(let i = year - 10; i <= year + 10; i++) {
      years.push(i)
    }

    const generateMonthDays = () => {
      console.log(date.year, date.month)
      const firstWeekDay = new Date(date.year, date.month - 1, 1).getDay();
      console.log(firstWeekDay,'周几')
			const startDate = new Date(date.year, date.month - 1, 1).getTime() - firstWeekDay * 24 * 60 * 60 * 1000;
      console.log(startDate)
      days.value = []
			for (let i = 0; i < 42; i++) {
				const nowDate = new Date(startDate + i * 24 * 60 * 60 * 1000);
        
				days.value.push({
					nowDate,
					year: nowDate.getFullYear(),
					month: nowDate.getMonth() + 1,
					day: nowDate.getDate(),
					date: `${nowDate.getFullYear()}-${
						nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1
					}-${nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate()}`,
          isActive: false,
				});

        // console.log(days)
			}
		};
    const currentMonthDays = computed(() => days.value.filter(item => {
        return item.month === date.month
    })
    )
    // console.log(currentMonthDays, '当前月多少天')
    const prevMonthDays = computed(() => days.value.filter(item => {
      if(date.year > item.year && item.month != date.month) {
        return item
      }
      if(date.year === item.year) {
        return item.month < date.month
      }
      
      
    }))
    // console.log(prevMonthDays, '上个月多少天')
    const nextMonthDays = computed(() => days.value.filter(item => {
      // 换年 12 月
      if(date.year < item.year) {
        // console.log('小于年份')
        return item
      } else if(date.year > item.year ) {
        // console.log('大于年份')
        return ''
      } else {
        if(date.year === item.year) {
          // console.log('同年份')
          // console.log(item.year, item.month, item.day)
          return item.month > date.month
        }
        
      }
      
      
    }))

    // console.log(nextMonthDays, '下个月多少天')

    onMounted(() => { 
      // 生成当月日历
			const { year, month, day } = getYearMonthDay();
      console.log(year, month, day)
			date.year = year;
			date.month = month;
			date.day = day;

      generateMonthDays()
      

      currentMonth.value = months[month - 1]
      currentYear.value = years[years.indexOf(year)]

      // 今天周几
      
      weekStartAndEnd(date.year, date.month, date.day, weekday())
      
    })

    // 计算 选中时间一周的起始
    /**
     * weekDay: 周几
     */
    const weekday = () => {
      return new Date(date.year, date.month - 1, date.day).getDay()
    }
    const weekStartAndEnd = (year: number, month:  number ,day:  number ,weekDay:  number) => {
      console.log('weekStartAndEnd', year, month, day, weekDay)
      let week = 7
      // console.log(week - weekDay)
      
      // 今天离周日还有几天
      let endlength = week - weekDay
      lastweek.value = year + '-' + month + '-' + (day + endlength)
      // 根据周日时间 计算 周一
      // 说明是上个月
      if(day + endlength - (week) < 0) {
        // 拿到上个月的天数
        let prevDayLength = new Date(year, month - 1, 0).getDate()
        firstweek.value = year + '-' + (month - 1) + '-' + ((prevDayLength) + (day + endlength - (week -1)))
      } else {
        // 当月
        // let currentDayLength = currentMonthDays.value.length
        let currentDayLength = new Date(year, month, 0).getDate()

        // console.log(month, currentDayLength, '天数', new Date(year, month, 0).getDate())
        // 下个月的多余天数
        let nextDaylength = day + endlength - currentDayLength
        // 下个月
        if(day + endlength - currentDayLength > 0) {
          // console.log('进来了1', year, month, nextDaylength)
          lastweek.value = year + '-' + (month + 1) + '-' + (nextDaylength)
        }
        // 如果是周末
        if(weekDay === 0 ) {
          let prevDayLength = new Date(year, month - 1, 0).getDate()
          lastweek.value = year + '-' + month + '-' + (day + endlength - (week))
          // 根据最后
          if((day + endlength - (week)) - week < 0) {
            firstweek.value = year + '-' + (month - 1) + '-' + (prevDayLength - (week - day - 1))
          } else {
            firstweek.value = year + '-' + month + '-' + ((day + endlength - (week)) - (week - 1))
          }
        } else {
          firstweek.value = year + '-' + month + '-' + (day + endlength - (week - 1))
        }
        
      }
      
      ctx.emit('getWeeks', firstweek.value, lastweek.value)
      console.log(firstweek.value , lastweek.value)
    }

    const prevMonth = () => {
      console.log('上个月')
      if (date.month === 1) {
          date.year--;
          date.month = 12;
        } else {
          date.month--;
        }
      const { year, month, day } = getYearMonthDay(new Date(date.year, date.month - 1, 1));
      date.year = year;
			date.month = month;
			date.day = day;

      currentMonth.value = months[month - 1]
      generateMonthDays()
    }

    const nextMonth = () => {
      console.log('下个月')
      if (date.month === 12) {
				date.year++;
				date.month = 1;
			} else {
				date.month++;
			}

      const { year, month, day } = getYearMonthDay(new Date(date.year, date.month - 1, 1));
			date.year = year;
			date.month = month;
			date.day = day;

      currentMonth.value = months[month - 1]
      generateMonthDays()
    }

    const handleCommandYear = (year: number) => {
      // console.log(year, '几年')
      date.year = years[years.indexOf(year)]
      // console.log(date.year, date.month)
      currentYear.value = years[years.indexOf(year)]
      

      generateMonthDays()
    }

    const handleCommandMonth = (month: string) => {
      // console.log(month, '几月')
      date.month = months.indexOf(month) + 1
      // console.log(date.year, date.month)
      currentMonth.value = months[date.month - 1]
      generateMonthDays()
    }

    const handleDay = (d: any) => {
      console.log(d)
      console.log(d.month)
      // console.log('选中这天星期几', new Date(d.year, d.month - 1, d.day).getDay())
      let currentToday =  new Date(d.year, d.month - 1, d.day).getDay()
      // console.log('选中这天星期几', currentToday)
      // 判断是 周 还是 日
      if(type.value === 'day') {
        activeDate.value = d.date
        firstweek.value = d.date
        lastweek.value = ''
        ctx.emit('getDays', firstweek.value)

        // 切换类型
        days.value.forEach(item => item.isActive = false)
      } else {
        // console.log('周', currentToday)
          let currentDayLength = currentMonthDays.value.length
          if(d.year === date.year && d.month === date.month) {
            // 如果是周一
            if(currentToday === 1) {
              firstweek.value = d.date

              let year = date.year
              let month = date.month
              // 说明是本年 本月
              let day = d.day + 6

              console.log(day)
              if(day - currentDayLength <= 0) {
                console.log('没有超过')
                lastweek.value = year + '-' + month  + '-' + day
              } else {
                console.log('超过')
                month = date.month + 1
                day = day - currentDayLength
                lastweek.value = year + '-' + month  + '-' + day
              }
            }
            weekStartAndEnd(d.year, d.month, d.day, currentToday)
            
          } else {
            // console.log('不是同一个月', d.year, d.month, d.day, currentToday)
            
            weekStartAndEnd(d.year, d.month, d.day, currentToday)
          }
          days.value.forEach(item => item.isActive = false)
          let arr = getAllDays(firstweek.value, lastweek.value)
          arr.forEach(day => {
            days.value.forEach(item => {
              
              if(day === item.date) {
                item.isActive = true
              }
            })
          })

          // ctx.emit('getWeeks', firstweek.value, lastweek.value)
        
        
          // console.log(arr)
          // console.log(days.value)
      }
      if(d.year > date.year) {
        date.year = d.year
        date.month = 1;
        console.log(currentYear.value, date.month)
        currentYear.value = d.year
        currentMonth.value = months[date.month - 1]

        generateMonthDays()
      }
      if(d.year < date.year) {
        date.year = d.year
        currentYear.value = d.year
        if(d.month === '12') {
          date.month = d.month
        }
      }
      
      
      if(d.month === date.month) {
        date.month = d.month
      }
      if(d.month < date.month) {
        date.month = d.month
        currentMonth.value = months[d.month - 1]
        console.log(date.month, '小于')
        generateMonthDays()
      }
      if(d.month > date.month) {
        date.month = d.month
        currentMonth.value = months[d.month - 1]
        console.log(date.month, '大于')
        generateMonthDays()
      }
    }
    
    
    return {
      week,
      years,
      months,
      days,
      type,


      firstweek,
      lastweek,
      // refDay,

      ...toRefs(date),
      currentMonthDays,
      prevMonthDays,
      nextMonthDays,
      prevMonth,
      nextMonth,
      currentMonth,
      currentYear,
      activeDate,

      handleCommandYear,
      handleCommandMonth,
      handleDay,

    }
  },
  methods: {
    // handleDay(data: any, idx: number){
    //   console.log(this.$refs.refDay)
    // }
  }
})
</script>

<style lang="scss" scoped>
.calendar {
  width: 320px;
  height: 300px;
  background: white;
  box-shadow: 0 0 2px 1px #e9e9e9;
  .headr {
    height: 60px;
    line-height: 60px;
    display: flex;
    .dropdown {
      padding: 0 20px;
      margin-top: 20px;
      display: flex;
      .drop {
        padding-left: 15px;
      }
      & > .drop:nth-child(1) {
        padding: 0;
      }
    }
    .arrow {
      flex: 1;
      text-align: right;
      padding-right: 20px;
    }
  }
  .week {
    height: 40px;
    line-height: 40px;
    display: flex;
    justify-content: space-evenly;
    text-align: center;
    align-items: center;
    border-bottom: 1px solid #e9e9e9;
    box-sizing: border-box;
    font-size: 12px;
    color: #606266;
    .week-item {
      width: 30px;
      height: 30px;
      line-height: 30px;
    }
  }

  .panel-content {
    display: flex;
    flex-wrap: wrap;
    padding: 3px 10px;
    justify-content: space-between;
    .day-item {
      cursor: pointer;

      & > div {
        width: 25px;
        height: 25px;
        line-height: 25px;
        text-align: center;
        font-size: 12px;
        margin: 3px 8px;
      }

    }
    .isCurrentDay {
      color: $mainColor;
      font-size: 14px;
      font-weight: 600;
    }

    .isActiveDay {
      font-size: 14px;
      background: $mainColor;
      color: white;
      border-radius: 50%;
    }
    .weekActiveDay {
      font-size: 14px;
      background: $mainColor;
      color: white !important;
      opacity: .5;
    }

    .noCurrentDays {
      font-size: 12px;
      color: #c0c4cc;

    }
  }
}
</style>